var ccisave = {};
var isGroup = false;
var firstGroup = true;
var isFirst = true;
var saveStringData = "";
var prefix = "";
ccisave.save = function(divId) {
	isGroup = false;
	firstGroup = true;
	isFirst = true;
	
	saveStringData = "";
	var childId = $("#"+divId+" :first").attr("id");
	
	ccisave.makeJson(childId);
	ccisave.print(saveData);
};

var saveData;
ccisave.print = function(str) {
	$("#ta").append(str).append("\n");
};

ccisave.makeJson = function(divId) {
	var obj = {};
	var groupstr = prefix+"group";
	var titlestr = prefix+"title";
	var parentstr = prefix+"parent";
	var mainstr = prefix+"main";
	var idNumber = divId.split("_")[1];
	var groupboxs = $("[class^='"+groupstr+"']", "#"+divId).filter( function() {
	    if($(this).hasClass("group")) {
	    	return $(this);
	    }
	});
	
	$("[id^='"+titlestr+"_"+idNumber+"']", "#"+divId).filter( function() {
			obj.GroupType = $(this).text();
	});
	
	$("[id^='"+parentstr+"_"+idNumber+"']", "#"+divId).filter( function() {
		var pid = $(this).attr("id");
		var mainIdNumber = pid.split("_")[1];
		if(idNumber != mainIdNumber) return;
		var loopCount = $("[id^='"+mainstr+"_"+mainIdNumber+"']", "#"+pid).size();
		var mainObject = $("[id^='"+mainstr+"_"+mainIdNumber+"']", "#"+pid);
		obj.values = [];
		for(var i=0; i<loopCount; i++) {
			var childObj = {};
			var child = mainObject[i];
			var childId = $(child).attr("id");
			childObj.name = $("#"+childId+" input")[0].value;
			childObj.value = $("#"+childId+" input")[1].value;
			childObj.restriction = $("#"+childId+" select option:selected").val();
			obj.values[i] = childObj;
			
		}
	});
	
	obj.groups = [];
	for(var i=0, length=groupboxs.length; i<length; i++) {
		var box = groupboxs[i];
		var boxid = $(box).attr("id");
		if(!ccisave.checkPreviousCalled(boxid)) {
			calledArr.push(boxid);
			obj.groups[i] = ccisave.makeJson($(box).attr("id"));
		}
	}
	
	saveData = JSON.stringify(obj);
	return obj;
};

var calledArr = [];
ccisave.checkPreviousCalled = function(id) {
	for(var i=0; i<calledArr.length; i++) {
		if(calledArr[i] == id) return true;
	}
	
	return false;
};

